{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YGa6S0ZD_M-6"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Download CIFAR-10 dataset\n",
        "(train_images, _), (test_images, _) = tf.keras.datasets.cifar10.load_data()\n",
        "train_images = train_images.astype('float32') / 255.0\n",
        "test_images = test_images.astype('float32') / 255.0\n",
        "\n",
        "# Define the autoencoder model\n",
        "input_dim = train_images.shape[1:]\n",
        "encoding_dim = 128\n",
        "\n",
        "# Encoder layers\n",
        "encoder = tf.keras.Sequential([\n",
        "  tf.keras.layers.Flatten(input_shape=input_dim),\n",
        "  tf.keras.layers.Dense(encoding_dim, activation='relu'),\n",
        "  tf.keras.layers.Dense(encoding_dim // 2, activation='relu')\n",
        "])\n",
        "\n",
        "# Decoder layers\n",
        "decoder = tf.keras.Sequential([\n",
        "  tf.keras.layers.Dense(encoding_dim // 2, activation='relu'),\n",
        "  tf.keras.layers.Dense(encoding_dim, activation='relu'),\n",
        "  tf.keras.layers.Dense(np.prod(input_dim), activation='sigmoid'),\n",
        "  tf.keras.layers.Reshape(input_dim)\n",
        "])\n",
        "\n",
        "# Autoencoder model\n",
        "autoencoder = tf.keras.Sequential([encoder, decoder])\n",
        "\n",
        "# Compile the model\n",
        "autoencoder.compile(optimizer='adam', loss='binary_crossentropy')\n",
        "\n",
        "# Train the autoencoder\n",
        "autoencoder.fit(train_images, train_images,\n",
        "                epochs=10,\n",
        "batch_size=128,\n",
        "                shuffle=True,\n",
        "validation_data=(test_images, test_images))\n",
        "\n",
        "# Visualize input and output data\n",
        "n = 10  # Number of images to visualize\n",
        "plt.figure(figsize=(20, 4))\n",
        "\n",
        "for i in range(n):\n",
        "    # Original images\n",
        "    ax = plt.subplot(2, n, i + 1)\n",
        "plt.imshow(train_images[i])\n",
        "plt.title(\"Original\")\n",
        "plt.gray()\n",
        "ax.get_xaxis().set_visible(False)\n",
        "ax.get_yaxis().set_visible(False)\n",
        "\n",
        "    # Reconstructed images\n",
        "    ax = plt.subplot(2, n, i + n + 1)\n",
        "    reconstructed = autoencoder.predict(np.expand_dims(train_images[i], axis=0))\n",
        "plt.imshow(reconstructed[0])\n",
        "plt.title(\"Reconstructed\")\n",
        "plt.gray()\n",
        "ax.get_xaxis().set_visible(False)\n",
        "ax.get_yaxis().set_visible(False)\n",
        "\n",
        "plt.show()\n"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Download MNIST dataset\n",
        "(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()\n",
        "train_images = train_images.astype('float32') / 255.0\n",
        "test_images = test_images.astype('float32') / 255.0\n",
        "\n",
        "# Download Fashion MNIST dataset\n",
        "(fashion_train_images, _), (fashion_test_images, _) = tf.keras.datasets.fashion_mnist.load_data()\n",
        "fashion_test_images = fashion_test_images.astype('float32') / 255.0\n",
        "\n",
        "# Isolate Trouser image and save to path\n",
        "Trouser_image = fashion_test_images[5]  # Assuming the Trouser image is at index 8\n",
        "plt.imshow(Trouser_image, cmap='gray')\n",
        "plt.axis('off')\n",
        "plt.savefig('Trouser_image.png')\n",
        "\n",
        "# Define and train the autoencoder on MNIST dataset\n",
        "input_dim = train_images.shape[1:]\n",
        "encoding_dim = 32\n",
        "\n",
        "# Encoder layers\n",
        "encoder = tf.keras.Sequential([\n",
        "    tf.keras.layers.Flatten(input_shape=input_dim),\n",
        "    tf.keras.layers.Dense(encoding_dim, activation='relu')\n",
        "])\n",
        "\n",
        "# Decoder layers\n",
        "decoder = tf.keras.Sequential([\n",
        "    tf.keras.layers.Dense(np.prod(input_dim), activation='sigmoid'),\n",
        "    tf.keras.layers.Reshape(input_dim)\n",
        "])\n",
        "\n",
        "# Autoencoder model\n",
        "autoencoder = tf.keras.Sequential([encoder, decoder])\n",
        "\n",
        "# Compile the model\n",
        "autoencoder.compile(optimizer='adam', loss='binary_crossentropy')\n",
        "\n",
        "# Train the autoencoder on MNIST dataset\n",
        "autoencoder.fit(train_images, train_images,\n",
        "                epochs=10,\n",
        "                batch_size=128,\n",
        "                shuffle=True,\n",
        "                validation_data=(test_images, test_images))\n",
        "\n",
        "# Reshape Trouser image for testing\n",
        "Trouser_image_reshaped = Trouser_image.reshape(1, *input_dim)\n",
        "\n",
        "# Use the trained autoencoder to reconstruct the Trouser image\n",
        "reconstructed_Trouser = autoencoder.predict(Trouser_image_reshaped)\n",
        "\n",
        "# Visualize the input Trouser image and reconstructed Trouser image\n",
        "plt.figure(figsize=(8, 4))\n",
        "plt.subplot(1, 2, 1)\n",
        "plt.imshow(Trouser_image, cmap='gray')\n",
        "plt.title('Input Trouser Image')\n",
        "plt.axis('off')\n",
        "plt.subplot(1, 2, 2)\n",
        "plt.imshow(reconstructed_Trouser[0], cmap='gray')\n",
        "plt.title('Reconstructed Trouser Image')\n",
        "plt.axis('off')\n",
        "plt.show()\n",
        "# Set the threshold for anomaly detection\n",
        "threshold = 0.08\n",
        "# Print anomaly detection result\n",
        "\n",
        "if reconstruction_errors[anomaly_index] > threshold:  # Define a threshold based on the application\n",
        "    print(\"Anomaly detected: The Trouser image is likely an anomaly.\")\n",
        "else:\n",
        "    print(\"No anomaly detected.\")\n"
      ],
      "metadata": {
        "id": "HY2dHUHX_qQj"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Download MNIST dataset\n",
        "(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()\n",
        "train_images = train_images.astype('float32') / 255.0\n",
        "test_images = test_images.astype('float32') / 255.0\n",
        "\n",
        "# Download Fashion MNIST dataset\n",
        "(_, _), (fashion_test_images, _) = tf.keras.datasets.fashion_mnist.load_data()\n",
        "fashion_test_images = fashion_test_images.astype('float32') / 255.0\n",
        "\n",
        "# Isolate sandal image and save to path\n",
        "sandal_image = fashion_test_images[8]  # Assuming the sandal image is at index 5\n",
        "plt.imshow(sandal_image, cmap='gray')\n",
        "plt.axis('off')\n",
        "plt.savefig('sandal_image.png')\n",
        "\n",
        "# Define and train the autoencoder on MNIST dataset\n",
        "input_shape = train_images.shape[1:]\n",
        "encoding_dim = 32\n",
        "\n",
        "# Encoder layers\n",
        "encoder = tf.keras.Sequential([\n",
        "    tf.keras.layers.Reshape(input_shape + (1,), input_shape=input_shape),\n",
        "    tf.keras.layers.Conv2D(16, (3, 3), activation='relu', padding='same'),\n",
        "    tf.keras.layers.MaxPooling2D((2, 2), padding='same'),\n",
        "    tf.keras.layers.Conv2D(8, (3, 3), activation='relu', padding='same'),\n",
        "    tf.keras.layers.MaxPooling2D((2, 2), padding='same'),\n",
        "    tf.keras.layers.Flatten(),\n",
        "    tf.keras.layers.Dense(encoding_dim, activation='relu')\n",
        "])\n",
        "\n",
        "# Decoder layers\n",
        "decoder = tf.keras.Sequential([\n",
        "    tf.keras.layers.Dense(np.prod((7, 7, 8)), activation='relu'),\n",
        "    tf.keras.layers.Reshape((7, 7, 8)),\n",
        "    tf.keras.layers.Conv2DTranspose(16, (3, 3), strides=(2, 2), activation='relu', padding='same'),\n",
        "    tf.keras.layers.Conv2DTranspose(1, (3, 3), strides=(2, 2), activation='sigmoid', padding='same')\n",
        "])\n",
        "\n",
        "# Autoencoder model\n",
        "autoencoder = tf.keras.Sequential([encoder, decoder])\n",
        "\n",
        "# Compile the model\n",
        "autoencoder.compile(optimizer='adam', loss='binary_crossentropy')\n",
        "\n",
        "# Reshape and normalize train and test images for CNN\n",
        "train_images_cnn = train_images.reshape(-1, *input_shape, 1)\n",
        "test_images_cnn = test_images.reshape(-1, *input_shape, 1)\n",
        "\n",
        "# Train the autoencoder on MNIST dataset\n",
        "autoencoder.fit(train_images_cnn, train_images_cnn,\n",
        "                epochs=10,\n",
        "                batch_size=128,\n",
        "                shuffle=True,\n",
        "                validation_data=(test_images_cnn, test_images_cnn))\n",
        "\n",
        "# Reshape sandal image for testing\n",
        "sandal_image_reshaped = sandal_image.reshape(1, *input_shape, 1)\n",
        "\n",
        "# Use the trained autoencoder to reconstruct the sandal image\n",
        "reconstructed_sandal = autoencoder.predict(sandal_image_reshaped)\n",
        "\n",
        "# Visualize the input sandal image and reconstructed sandal image\n",
        "plt.figure(figsize=(8, 4))\n",
        "plt.subplot(1, 2, 1)\n",
        "plt.imshow(sandal_image, cmap='gray')\n",
        "plt.title('Input Sandal Image')\n",
        "plt.axis('off')\n",
        "plt.subplot(1, 2, 2)\n",
        "plt.imshow(reconstructed_sandal[0, ..., 0], cmap='gray')\n",
        "plt.title('Reconstructed Sandal Image')\n",
        "plt.axis('off')\n",
        "plt.show()\n"
      ],
      "metadata": {
        "id": "24Wa07vsAAYq"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}